#include<iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <thread>
#include"TcpSocket.hpp"
void threadroutine(int newsockfd)
{
    char buf[2049]={0};//定义缓冲区，大小2048，最后一个填充\0
    while(1)
    {
        int size=read(newsockfd,buf,2048);
        if(size>0)
        {
            //输出读到的内容
            buf[size]='\0';
            std::cout<<"server readed: "<<buf<<std::endl; 
            //回显一个字符串
            write(newsockfd,buf,size);
        }
        else if(size==0)
        {
            std::cout<<"client close the connection"<<std::endl;
            break;
        }
        else
        {
            perror("server read socket fail");
            break;
        }
    }
    close(newsockfd);
}
int main()
{
    TcpSocket tc;
    if(tc.Initialization()==false)
    {
        std::cerr<<"TcpSocket Initialization error"<<std::endl;
        return 0;
    }
    
    while(1)
    {
        int new_sock_fd =tc.AcceptConnection();//主线程阻塞到这里接收连接
        if(new_sock_fd==-1)
        {
            std::cerr<<"accept error"<<std::endl;
            continue;
        }
        else
        {
            std::cout<<"accept a new connection"<<std::endl;
        }
        //创建一个线程来提供服务
        std::thread t(threadroutine,new_sock_fd);
        t.detach();
    }
    
    
    return 0;
}